﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using Commerce.Common;

namespace Commerce.Promotions
{
    public class DollarsOffByProductCoupon : Coupon
    {
        public DollarsOffByProductCoupon()
            : base()
        {

        }

        public DollarsOffByProductCoupon(string couponCode, CouponType couponType)
            : base(couponCode, couponType)
        {
        }
        private int _dollarsOff;

        public int DollarsOff
        {
            get { return _dollarsOff; }
            set { _dollarsOff = value; }
        }

        private List<int> _productToBuy;

        [SelectorType("ProductPicker", multiSelect = true)]
        public List<int> ProductToBuy
        {
            get { return _productToBuy; }
            set { _productToBuy = value; }
        }

        decimal CalculateDiscountAmount(decimal itemAmount)
        {

            decimal result = 0;
            decimal dDollars = Convert.ToDecimal(DollarsOff);
            if (dDollars > 0)
            {
                if (dDollars < itemAmount)
                {
                    return dDollars;
                }
            }

            return result;
        }

        public override bool ApplyCouponToOrder(Commerce.Common.Order order)
        {
            //Validate the order to make sure it's good.  
            CouponValidationResponse validationResponse =
                ValidateCouponForOrder(order);
            if (!validationResponse.IsValid)
            {
                throw new ArgumentException("Coupon is not valid for order: " + validationResponse, "order");
            }


            List<int> selected = new List<int>();
            XDocument doc = XDocument.Parse(base.GetXmlData());

            if (doc.Descendants("ProductToBuy").Descendants("int").Count() > 0)
            {
                foreach (XElement element in doc.Descendants("ProductToBuy").Descendants("int"))
                {
                    selected.Add(Int32.Parse(element.Value));
                }
            }
            else
            {
                throw new ArgumentException("No products selected for coupon.");
            }

            //if (!order.CouponCodes.Contains(CouponCode))
            //{

                order.DiscountAmount = 0;

                foreach (var o in order.Items)
                {
                    if (selected.Exists(delegate(int i) { return i == o.ProductID; }) == true)
                    {
                        order.DiscountAmount += CalculateDiscountAmount(o.LineTotal);
                    }
                }

                //add a comment to the order
                order.CouponCodes = CouponCode;

                //save the order
                order.Save("Coupon System");
            //}

            return false;
        }
    }
}
